#!/bin/bash

# 构建脚本
# 用法: ./scripts/build.sh [debug|release] [options]

set -e  # 遇到错误立即退出

# 默认参数
BUILD_TYPE="Debug"
BUILD_DIR="build"
ENABLE_ASAN=OFF
ENABLE_COVERAGE=OFF
ENABLE_TESTING=ON
CLEAN_BUILD=false

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 打印帮助信息
print_help() {
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  debug              构建Debug版本 (默认)"
    echo "  release            构建Release版本"
    echo "  --asan             启用AddressSanitizer"
    echo "  --coverage         启用代码覆盖率"
    echo "  --no-tests         不构建测试"
    echo "  --clean            清理后重新构建"
    echo "  --build-dir <dir>  指定构建目录 (默认: build)"
    echo "  -h, --help         显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 debug --asan"
    echo "  $0 release --clean"
}

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        debug)
            BUILD_TYPE="Debug"
            shift
            ;;
        release)
            BUILD_TYPE="Release"
            shift
            ;;
        --asan)
            ENABLE_ASAN=ON
            shift
            ;;
        --coverage)
            ENABLE_COVERAGE=ON
            shift
            ;;
        --no-tests)
            ENABLE_TESTING=OFF
            shift
            ;;
        --clean)
            CLEAN_BUILD=true
            shift
            ;;
        --build-dir)
            BUILD_DIR="$2"
            shift 2
            ;;
        -h|--help)
            print_help
            exit 0
            ;;
        *)
            echo -e "${RED}错误: 未知参数 '$1'${NC}"
            print_help
            exit 1
            ;;
    esac
done

# 获取脚本所在目录的父目录（项目根目录）
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

cd "$PROJECT_DIR"

echo -e "${GREEN}=== C++ 项目构建脚本 ===${NC}"
echo "项目目录: $PROJECT_DIR"
echo "构建类型: $BUILD_TYPE"
echo "构建目录: $BUILD_DIR"
echo "AddressSanitizer: $ENABLE_ASAN"
echo "代码覆盖率: $ENABLE_COVERAGE"
echo "构建测试: $ENABLE_TESTING"
echo ""

# 清理构建目录
if [ "$CLEAN_BUILD" = true ]; then
    echo -e "${YELLOW}清理构建目录...${NC}"
    rm -rf "$BUILD_DIR"
fi

# 创建构建目录
mkdir -p "$BUILD_DIR"
cd "$BUILD_DIR"

# 运行CMake配置
echo -e "${GREEN}运行CMake配置...${NC}"
cmake .. \
    -DCMAKE_BUILD_TYPE="$BUILD_TYPE" \
    -DENABLE_ASAN="$ENABLE_ASAN" \
    -DENABLE_COVERAGE="$ENABLE_COVERAGE" \
    -DBUILD_TESTING="$ENABLE_TESTING" \
    -DCMAKE_EXPORT_COMPILE_COMMANDS=ON

# 构建项目
echo -e "${GREEN}构建项目...${NC}"
cmake --build . --config "$BUILD_TYPE" -j$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)

echo -e "${GREEN}构建成功！${NC}"
echo "可执行文件位于: $BUILD_DIR/bin/"
echo "库文件位于: $BUILD_DIR/lib/"

if [ "$ENABLE_TESTING" = "ON" ]; then
    echo -e "${YELLOW}提示: 运行 './scripts/test.sh' 来执行测试${NC}"
fi
